﻿namespace AddressBook.Business.Contact
{
	#region "Using Statements"
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;

	using Csla;
	using Csla.Data;
	#endregion

	[Serializable]
	public class FamilyMembers : BusinessListBase<FamilyMembers, FamilyMember>
	{
		#region "Business Methods"

		public FamilyMember GetItem(Int32 contactId)
		{
			foreach (FamilyMember member in this)
			{
				if (member.ContactId == contactId)
				{
					return member;
				}
			}

			return null;
		}

		public void Add(Int32 contactId)
		{
			if (!(Contains(contactId)))
			{
				FamilyMember resource = FamilyMember.NewFamilyMember(contactId);
				this.Add(resource);
			}
			else
			{
				throw new InvalidOperationException("Contact is already a member of this family");
			}
		}

		public void Remove(Int32 contactId)
		{
			foreach (FamilyMember member in this)
			{
				if (member.ContactId == contactId)
				{
					Remove(member);
					break;
				}
			}
		}

		public bool Contains(Int32 contactId)
		{
			foreach (FamilyMember member in this)
			{
				if (member.ContactId == contactId)
				{
					return true;
				}
			}
			return false;
		}

		public bool ContainsDeleted(Int32 contactId)
		{
			foreach (FamilyMember member in DeletedList)
			{
				if (member.ContactId == contactId)
				{
					return true;
				}
			}
			return false;
		}

		#endregion

		#region "Factory Methods"

    internal static FamilyMembers NewFamilyMembers()
    {
      return DataPortal.CreateChild<FamilyMembers>();
    }

		internal static FamilyMembers GetFamilyMembers(AddressBook.Business.Model.FamilyMember[] data)
    {
      return DataPortal.FetchChild<FamilyMembers>(data);
    }

		private FamilyMembers()
    { /* require use of factory methods */ }

    #endregion

		#region "Data Access"

		private void Child_Fetch(AddressBook.Business.Model.FamilyMember[] data)
		{
			if (data == null) return;

			this.RaiseListChangedEvents = false;

			foreach (var value in data)
			{
				this.Add(FamilyMember.GetFamilyMember(value));
			}

			this.RaiseListChangedEvents = true;
		}

		#endregion
	}
}
